package com.xm.xmapp;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.model.NaviLatLng;
import com.android.volley.VolleyError;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.Type;
import com.xm.xmapp.app.Type.F_ShortTimeRentcar;
import com.xm.xmapp.base.BaseActivity;
import com.xm.xmapp.customview.CustomLayout;
import com.xm.xmapp.customview.TipDialog;
import com.xm.xmapp.dialog.HCDialog;
import com.xm.xmapp.fragment.ShortTimeRentcarFragment;
import com.xm.xmapp.map.ClusterItem;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.myinterface.MyDialogButton;
import com.xm.xmapp.request.bean.Get_user_money_infoRequest;
import com.xm.xmapp.request.bean.Get_user_order_moneyRequest;
import com.xm.xmapp.request.bean.Pay_order_infoRequest;
import com.xm.xmapp.response.bean.BaseBeanResponse;
import com.xm.xmapp.response.bean.ResponseAppUserOrder;
import com.xm.xmapp.response.bean.ResponseUserCouponsList;
import com.xm.xmapp.response.bean.ResponseUserMoney;
import com.xm.xmapp.response.bean.ResponseUserOrderMoney;
import com.xm.xmapp.tools.MyCache;
import com.xm.xmapp.tools.StringTools;
import com.xm.xmapp.tools.TimeUtil;
import com.xm.xmapp.tools.TimeUtil.TimeListener;
import com.xm.xmapp.tools.Tools;
import com.xm.xmapp.wxapi.WXPayEntryActivity;

public class ShortTimeOrderPayActivity extends BaseActivity implements OnClickListener {

	private TextView tv_paymoney, tv_user_money, tv_car_on_time, tv_car_off_time, tv_car_on_money, tv_car_off_money,
			tishi;
	/**
	 * 优惠券
	 */
	public static final int YHQCode = 5;

	private TextView tv_button, tv_go_pay, btn_get_verify;
	private ResponseUserOrderMoney base;
	private ResponseUserMoney bean;
	private ResponseUserCouponsList mUserCouponsBean;
	private CustomLayout shifu, day, daymoney, daymoneytop, service_money;
	private double shifuMoney;
	private String user_coupons_id;
	private HCDialog myDialog;
	private ResponseAppUserOrder orderid;// 还车订单ID

	private TimeUtil task = new TimeUtil(2 * MyAppcation.getMyAppcation().get_money_second * 1000,
			MyAppcation.getMyAppcation().get_money_second * 1000);// 定时任务，每个一段时间获取订单金额

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hc);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		task.cancel();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (MyAppcation.getMyAppcation().getUserBean() != null)
			task.start();

	}

	@Override
	protected void onPause() {
		super.onPause();
		task.cancel();
	}

	@Override
	public void initView() {

		tv_paymoney = (TextView) findViewById(R.id.tv_paymoney);
		tv_user_money = (TextView) findViewById(R.id.tv_user_money);
		tv_car_on_time = (TextView) findViewById(R.id.tv_car_on_time);
		tv_car_off_time = (TextView) findViewById(R.id.tv_car_off_time);
		tv_car_on_money = (TextView) findViewById(R.id.tv_car_on_money);
		tv_car_off_money = (TextView) findViewById(R.id.tv_car_off_money);

		tv_button = (TextView) findViewById(R.id.tv_button);
		tv_go_pay = (TextView) findViewById(R.id.tv_go_pay);
		shifu = (CustomLayout) findViewById(R.id.shifu);
		day = (CustomLayout) findViewById(R.id.day);
		daymoney = (CustomLayout) findViewById(R.id.daymoney);
		daymoneytop = (CustomLayout) findViewById(R.id.daymoneytop);
		service_money = (CustomLayout) findViewById(R.id.service_money);
		tishi = (TextView) findViewById(R.id.tishi);
		btn_get_verify = (TextView) findViewById(R.id.btn_get_verify);

	}

	@Override
	public void initData() {

		tishi.setText("计费出现问题，请致电客服：" + CodeConstant.phone);
		orderid = (ResponseAppUserOrder) getIntent().getSerializableExtra("bean");

		setMyTitle("还车");
		get_user_money_infoRequest();

	}

	private void get_user_money_infoRequest() {

		Get_user_money_infoRequest requestBean = new Get_user_money_infoRequest();
		promptDialog.show();
		GetDataInterFace<String> listener = new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {
				promptDialog.dismiss();
				bean = JSON.parseObject(response, ResponseUserMoney.class);
				tv_user_money.setText(bean.user_money + "");
			}
		};

		/**
		 * 先显示缓存数据
		 */
		String response = MyCache.getMyCache().getCache(requestBean.getCacheString());
		if (response != null && !response.equals("")) {
			listener.onResponse(response);
		}

		MyAppcation.getMyAppcation().getPostData(this, requestBean, listener, new DisssmissInterFace() {

			@Override
			public void putError(VolleyError error) {
				promptDialog.dismiss();
			}
		});

		task.setTimeListener(new TimeListener() {

			@Override
			public void timeOnTick(long time) {

				Get_user_order_moneyRequest requestBean = new Get_user_order_moneyRequest();
				requestBean.order_id = orderid.order_id;
				requestBean.sim = orderid.tbox_sim;
				MyAppcation.getMyAppcation().getPostData(ShortTimeOrderPayActivity.this, requestBean,
						new GetDataInterFace<String>() {

							@Override
							public void onResponse(String response) {

								promptDialog.dismiss();
								BaseBeanResponse<String> baseBean = JSON.parseObject(response,
										new TypeReference<BaseBeanResponse<String>>() {
										});
								if (baseBean.errCode == 10004) {
									/**
									 * 订单不存在
									 */
									setResult(CodeConstant.HCActivity, getIntent());
									finish();

								} else if (baseBean.errCode == 0) {
									base = JSON.parseObject(baseBean.data, ResponseUserOrderMoney.class);
									setData(base);
								} else {

								}

							}

						}, new DisssmissInterFace() {

							@Override
							public void putError(VolleyError error) {
								promptDialog.dismiss();
							}
						});
			}

			@Override
			public void timeFinish() {
				task.cancel();
				task.start();
			}
		});
		promptDialog.show();
		task.start();

	}

	/**
	 * 设置数据
	 * 
	 * @param base
	 */
	private void setData(ResponseUserOrderMoney base) {

		tv_paymoney.setText(base.money + "");
		submitMoney();
		DecimalFormat decimalFormat = new DecimalFormat("0.00");// 构造方法的字符格式这里如果小数不足2位,会以0补足.
		String p = decimalFormat.format(Double.parseDouble(base.orderMoneyInfoArr.today_max_money));// format
																									// 返回的是字符串
		daymoneytop.setText2(p + "元/天");
		int hour1 = Integer.parseInt(base.orderMoneyInfoArr.car_on_minute_total) / 60;
		int min1 = Integer.parseInt(base.orderMoneyInfoArr.car_on_minute_total) % 60;
		tv_car_on_time.setText((hour1 % 24 == 0 ? "" : (hour1 % 24 + "小时")) + min1 + "分钟");
		tv_car_on_money.setText(base.orderMoneyInfoArr.car_on_money_total + "元");

		int hour2 = Integer.parseInt(base.orderMoneyInfoArr.car_off_minute_total) / 60;
		int min2 = Integer.parseInt(base.orderMoneyInfoArr.car_off_minute_total) % 60;
		tv_car_off_time.setText((hour2 % 24 == 0 ? "" : (hour2 % 24 + "小时")) + min2 + "分钟");
		tv_car_off_money.setText(base.orderMoneyInfoArr.car_off_money_total + "元");

		switch (base.orderMoneyInfoArr.is_lock_money) {
		case 0:
			tv_button.setText("还车");
			tv_button.setBackgroundResource(R.drawable.onclickbackground1);
			tv_button.setOnClickListener(ShortTimeOrderPayActivity.this);
			break;
		case 1:
			tv_button.setOnClickListener(null);
			tv_button.setText("被锁单");
			tv_button.setBackgroundResource(R.drawable.myborder4);
			break;
		default:
			tv_button.setText("还车");
			tv_button.setBackgroundResource(R.drawable.onclickbackground1);
			tv_button.setOnClickListener(ShortTimeOrderPayActivity.this);
			break;
		}

		if (base.orderMoneyInfoArr.today_money_times <= 0) {
			day.setVisibility(View.GONE);
		} else {
			day.setVisibility(View.VISIBLE);
			day.setText2(base.orderMoneyInfoArr.today_money_times + "天");
		}

		if (base.orderMoneyInfoArr.today_money_total <= 0) {
			daymoney.setVisibility(View.GONE);
		} else {
			daymoney.setVisibility(View.VISIBLE);
			daymoney.setText2(base.orderMoneyInfoArr.today_money_total + "元");
		}
	}

	/**
	 * 计算实付金额
	 */
	private void submitMoney() {

		boolean isIsbujia;
		if (base.orderMoneyInfoArr.starting_fare > base.onlineMoney) {
			isIsbujia = true;
		} else {
			isIsbujia = false;
		}

		if (mUserCouponsBean != null) {
			if (mUserCouponsBean.coupons_type == 1) {
				shifuMoney = base.money - Double.parseDouble(mUserCouponsBean.coupons_money + "");
			} else {
				shifuMoney = base.money * mUserCouponsBean.coupons_discount / 100;
			}
			shifuMoney = Double.parseDouble(StringTools.getString1(shifuMoney + ""));
			shifu.setText2((shifuMoney > 0 ? StringTools.formatFloatNumberMoney(shifuMoney) : "0") + "元");

		} else {
			shifuMoney = base.money;
			shifu.setText2(StringTools.formatFloatNumberMoney(base.money) + "元");
		}

		String str = "";

		if (base.orderMoneyInfoArr.send_car_service_money > 0) {
			service_money.setVisibility(View.VISIBLE);
			service_money.setText2(base.orderMoneyInfoArr.send_car_service_money + "元");
			if (isIsbujia) {
				str = "(起步价+服务费)";
			} else {
				str = "(含服务费)";
			}

		} else {
			service_money.setVisibility(View.GONE);
			if (isIsbujia) {
				str = "(起步价)";
			} else {
				str = "";
			}
		}
		shifu.setText1(StringTools.getStyle(4, str, "实付金额" + str, (int) (shifu.getText1Size() - 2)));

	}

	@Override
	public void initEvent() {

		tv_go_pay.setOnClickListener(this);
		findViewById(R.id.ll_yhq).setOnClickListener(this);
		switch (orderid.is_lock_money) {
		case 0:
			tv_button.setOnClickListener(this);
			break;
		case 1:
			tv_button.setOnClickListener(null);
			tv_button.setText("被锁单");
			tv_button.setBackgroundResource(R.drawable.myborder4);
			break;
		default:
			tv_button.setOnClickListener(this);
			break;
		}

	}

	@Override
	public void onClick(View arg0) {

		switch (arg0.getId()) {
		case R.id.tv_button:
			if (bean != null && bean.user_money >= shifuMoney) {
				if (base != null) {
					String tip = "你的还车费用是" + (shifuMoney > 0 ? shifuMoney : "0") + "元，是否立即还车?";
					TipDialog tipDialog = new TipDialog(this, "温馨提示", tip, new MyDialogButton() {

						@Override
						public void setTitle(int flag, String str) {
							pay_order_infoRequest();
						}
					});
					tipDialog.show();
				} else {
					Tools.showMessage("获取还车费用失败，请稍后再试！");
				}
			} else {
				TipDialog tipDialog = new TipDialog(this, "温馨提示", "钱包余额不足，去充值?", new MyDialogButton() {

					@Override
					public void setTitle(int flag, String str) {
						tv_go_pay.performClick();
					}
				});
				tipDialog.show();
			}

			break;
		case R.id.tv_go_pay:
			WXPayEntryActivity.currentStatus = WXPayEntryActivity.FENSHIHC;
			intent = new Intent(MyAppcation.getMyAppcation(), PayActivity.class);
			startActivity(intent);

			break;

		case R.id.ll_yhq:

			intent = new Intent(MyAppcation.getMyAppcation(), YHQActivity.class);
			intent.putExtra("flag", 1);
			intent.putExtra("bean", mUserCouponsBean);
			if (base != null)
				intent.putExtra("money", base.money);
			startActivityForResult(intent, YHQCode);

			break;
		default:
			break;
		}
	}

	private void pay_order_infoRequest() {

		if (base != null) {
			Pay_order_infoRequest requestBean = new Pay_order_infoRequest();
			requestBean.order_id = orderid.order_id;
			requestBean.money = base.money;
			requestBean.user_coupons_id = user_coupons_id;
			requestBean.time_sign = base.time_sign;
			promptDialog.show();
			MyAppcation.getMyAppcation().getPostData(this, requestBean, new GetDataInterFace<String>() {

				@Override
				public void onResponse(String response) {
					promptDialog.dismiss();
					BaseBeanResponse<String> data = JSON.parseObject(response,
							new TypeReference<BaseBeanResponse<String>>() {
							});

					switch (data.errCode) {
					case 0:
						Tools.showMessage("还车成功,请关好车门并携带好随身物品!");
						MyAppcation.getMyAppcation().notifyDataSetChanged(ShortTimeRentcarFragment.class, F_ShortTimeRentcar.DEFAULT);
						setResult(CodeConstant.HCActivity);
						finish();
						break;

					case 3003:
						startGuideHC();
						break;

					default:
						Tools.showMessage(data.errMsg);
						break;
					}

				}
			}, new DisssmissInterFace() {

				@Override
				public void putError(VolleyError error) {
					promptDialog.dismiss();
				}
			});
		} else {
			Tools.showMessage("获取还车费用失败，请稍后再试！");
		}

	}

	protected void startGuideHC() {

		@SuppressWarnings("unchecked")
		ArrayList<ClusterItem> list = (ArrayList<ClusterItem>) MyAppcation.getMyAppcation().notifyDataSetChanged(
				MainActivity.class, Type.A_Main.SHORT_RENT_CODE, null);
		final LatLng myLatLng = MyAppcation.getMyAppcation().getMyLocation();
		if (myLatLng != null) {
			if (list != null) {
				float min = AMapUtils.calculateLineDistance(MyAppcation.getMyAppcation().getMyLocation(), list.get(0)
						.getLatLng());
				int x = 0;
				for (int i = 0, size = list.size(); i < size; i++) {
					float temp = AMapUtils.calculateLineDistance(MyAppcation.getMyAppcation().getMyLocation(), list
							.get(i).getLatLng());
					if (min >= temp) {
						x = i;
						min = AMapUtils.calculateLineDistance(MyAppcation.getMyAppcation().getMyLocation(), list.get(i)
								.getLatLng());
					}
				}
				// 车辆此时的位置不在还车区域内，距离最近的还车地点(%@)还有%@，导航去这里？
				myDialog = new HCDialog(this, "温馨提示", list.get(x), "我知道了", new HCDialog.OnClickListener() {

					@Override
					public void onClick(ClusterItem item) {
						myDialog.dismiss();
						Intent intent = new Intent(MyAppcation.getMyAppcation(), BasicNaviActivity.class);
						NaviLatLng mEndLatlng = new NaviLatLng(item.getLatLng().latitude, item.getLatLng().longitude);
						NaviLatLng mStartLatlng = new NaviLatLng(myLatLng.latitude, myLatLng.longitude);
						intent.putExtra("mStartLatlng", mStartLatlng);
						intent.putExtra("mEndLatlng", mEndLatlng);
						startActivity(intent);
					}
				});
				myDialog.show();
			}
		} else {
			Tools.showMessage("未获取到您的位置信息，请稍后再试");
		}

	}

	/**
	 * 0充值成功后调用1极光推送，即后台还车后，在mainactivity调用
	 */
	@Override
	public Object dataChang(int flag, Object data) {
		switch (flag) {
		case Type.A_ShortTimeOrderPay.DEFAULT:
			get_user_money_infoRequest();
			break;
		case Type.A_ShortTimeOrderPay.HC:
			setResult(CodeConstant.HCActivity);
			finish();
			break;

		default:
			break;
		}

		return super.dataChang(flag, data);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case YHQCode:
			mUserCouponsBean = (ResponseUserCouponsList) data.getSerializableExtra("bean");
			submitMoney();
			if (mUserCouponsBean != null) {
				user_coupons_id = mUserCouponsBean.user_coupons_id;
				if (mUserCouponsBean.coupons_type == 1) {
					btn_get_verify.setText("已选择" + StringTools.formatFloatNumberMoney(mUserCouponsBean.coupons_money)
							+ "元现金券");
				} else {
					btn_get_verify.setText("已选择" + mUserCouponsBean.coupons_discount / 10 + "折折扣券");
				}
			} else {
				user_coupons_id = null;
				btn_get_verify.setText("请选择使用优惠券");
			}

			break;

		default:
			break;
		}

	}
}
